package com.imooc.trading_system.utils;

import com.imooc.trading_system.model.UserDO;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;

/**
 * @author Feng zhaoxi
 * @version 1.0
 * @date 2021/12/29 1:39 下午
 */
@Slf4j
public class JWTUtils {
    /**
     * 过期时间，一周
     */
    private static final long EXPIRE = 60000 * 60 * 24 * 7;
    //private  static final long EXPIRE = 1;


    /**
     * 加密秘钥
     */
    private static final String SECRET = "imooc.trading_system";


    /**
     * 令牌前缀
     */
    private static final String TOKEN_PREFIX = "JWT";


    /**
     * subject
     */
    private static final String SUBJECT = "trading_system";


    /**
     * 根据用户信息，生成令牌
     *
     * @param user
     * @return
     */
    public static String geneJsonWebToken(UserDO user) {

        String token = Jwts.builder().setSubject(SUBJECT)
//                .claim("head_img",user.getHeadImg())
                .claim("id", user.getId())
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
                .signWith(SignatureAlgorithm.HS256, SECRET).compact();

        token = TOKEN_PREFIX + " " + token;


        return token;
    }


    /**
     * 校验token的方法
     *
     * @param token
     * @return
     */
    public static Claims checkJWT(String token) {

        try {

            final Claims claims = Jwts.parser().setSigningKey(SECRET)
                    .parseClaimsJws(token.replace(TOKEN_PREFIX, "")).getBody();

            return claims;

        } catch (Exception e) {
            return null;
        }

    }

    public Object getUnionid(String token) {
        try {
            Claims claims = Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token.replace(TOKEN_PREFIX, "")).getBody();
            return claims.get("unionid");
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

}
